package com.jhws.sys.cms.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jhws.util.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Repository;

import com.jhws.core.db.BaseDao;

@Repository("com.jhws.sys.cms.dao.ResourceDao")
public class ResourceDao extends BaseDao {
    public List<Map<String, Object>> queryTypes(String parentCode) {
        String sql = "select * from cms_resource_type";
        if (!StringUtils.isEmpty(parentCode)) {
            List<Map<String, Object>> treeMap = new ArrayList<>();
            queryChild(treeMap, parentCode, null);
            return treeMap;
        }
        return j().queryForList(sql);
    }

    public List<Map<String, Object>> queryTypes(String parentCode, String select) {
        String sql;
        if (select != null) {
            sql = select + " from cms_resource_type";
        } else {
            sql = "select * from cms_resource_type";
        }
        if (!StringUtils.isEmpty(parentCode)) {
            List<Map<String, Object>> treeMap = new ArrayList<>();
            queryChild(treeMap, parentCode, select);
            return treeMap;
        }
        return j().queryForList(sql);
    }

    private void queryChild(List<Map<String, Object>> treeMap, String parentCode, String select) {
        String sql;
        if (select != null) {
            sql = select + " from cms_resource_type where parent_code = '" + parentCode + "'";
        } else {
            sql = "select * from cms_resource_type where parent_code = '" + parentCode + "'";
        }
        List<Map<String, Object>> subTypeIds = j().queryForList(sql);
        if (CollectionUtils.isNotEmpty(subTypeIds)) {
            treeMap.addAll(subTypeIds);
            for (Map<String, Object> map : subTypeIds) {
                String typeCode = MapUtils.getString(map, "type_code", "");
                queryChild(treeMap, typeCode, select);
            }
        }
    }
}
